package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ArticleFreemarkerService;
import com.heima.common.constant.ArticleConstants;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.search.vos.SearchArticleVo;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class ArticleFreemarkerServiceImpl implements ArticleFreemarkerService {

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private ApArticleContentMapper articleContentMapper;

    @Autowired
    private Configuration configuration;

    @Autowired
    private ApArticleMapper apArticleMapper;
    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;

    /**
     * 生成静态文件上传到minio
     *
     * @param article
     * @param content
     */
    @Override
    @Async //异步
    public void buildArticleToMinIO(ApArticle article, String content) {
        log.info("【文章内容生成静态html】");
        //文章内容通过freemarker生成html文件
        //判断文章内容是否为空
        if(content!=null && StringUtils.isNotBlank(content)){
            //文章内容不为空时
            try {
                Template template = configuration.getTemplate("article.ftl");
                Map<String, Object> data = new HashMap<>();
                data.put("content", JSON.parseArray(content));
                StringWriter out = new StringWriter();
                template.process(data,out);

                InputStream is = new ByteArrayInputStream(out.toString().getBytes());

                //3.将html文件上传到minio中
                //path - > 静态网页地址
                String path = fileStorageService.uploadHtmlFile("", article.getId() + ".html"
                        , is);

                log.info("【文章静态html页面网址】:{}",path);
                //修改ap_article表，保存static_url字段
                apArticleMapper.update(null, new LambdaUpdateWrapper<ApArticle>().
                        eq(ApArticle::getId, article.getId()).
                        set(ApArticle::getStaticUrl, path));

                //发送消息，创建索引
                log.info("【发送消息,创建索引】");
                createArticleESIndex(article,content,path);

            } catch (IOException | TemplateException e) {
                throw new RuntimeException(e);
            }
        }
    }

    /**
     * 发送消息,创建索引
     * @param article
     * @param content
     * @param path
     */
    private void createArticleESIndex(ApArticle article, String content, String path) {
        SearchArticleVo vo = new SearchArticleVo();
        BeanUtils.copyProperties(article,vo);
        vo.setContent(content);
        vo.setStaticUrl(path);
        kafkaTemplate.send(ArticleConstants.ARTICLE_ES_SYNC_TOPIC,JSON.toJSONString(vo));

    }
}
